package com.travel.commons.utils;

import com.travel.commons.exception.RRException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.Calendar;

/**
 * 订单号生成器
 * 时间戳：offset from 2021-01-01
 */
@Slf4j
public final class SnowNoGenerator {
    public static final long EPOCH;

    private static final long SEQUENCE_BITS = 12L;

    private static final long WORKER_ID_BITS = 10L;

    private static final long SEQUENCE_MASK = (1 << SEQUENCE_BITS) - 1;

    private static final long WORKER_ID_LEFT_SHIFT_BITS = SEQUENCE_BITS;

    private static final long TIMESTAMP_LEFT_SHIFT_BITS = WORKER_ID_LEFT_SHIFT_BITS + WORKER_ID_BITS;

    private static final long WORKER_ID_MAX_VALUE = 1L << WORKER_ID_BITS;

    @Value("snowFlake.workerId")
    private static long workerId;

    @Value("snowFlake.maxTolerateTime")
    private static int maxTolerateTimeDifferenceMilliseconds = 10;

    static {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2021, Calendar.FEBRUARY, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        EPOCH = calendar.getTimeInMillis();
    }

    private byte sequenceOffset;

    private long sequence;

    private long lastMilliseconds;

    public static void setWorkerId(final long workerId) {
        if (workerId < 0L || workerId >= WORKER_ID_MAX_VALUE) {
            throw new RRException("非法参数");
        }
        SnowNoGenerator.workerId = workerId;
    }

    public static void setMaxTolerateTimeDifferenceMilliseconds(final int maxTolerateTimeDifferenceMilliseconds) {
        SnowNoGenerator.maxTolerateTimeDifferenceMilliseconds = maxTolerateTimeDifferenceMilliseconds;
    }

    public synchronized String generate() {
        long currMilliseconds = System.currentTimeMillis();
        if (waitTolerateTimeDifferenceIfNeed(currMilliseconds)) {
            currMilliseconds = System.currentTimeMillis();
        }
        if (lastMilliseconds == currMilliseconds) {
            if (0L == (sequence = (sequence + 1) & SEQUENCE_MASK)) {
                currMilliseconds = waitUntilNextTime(currMilliseconds);
            }
        } else {
            vibrateSequenceOffset();
            sequence = sequenceOffset;
        }
        lastMilliseconds = currMilliseconds;
        return (((currMilliseconds - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (workerId << WORKER_ID_LEFT_SHIFT_BITS) | sequence) + "";
    }

    @SneakyThrows
    private boolean waitTolerateTimeDifferenceIfNeed(final long currMilliseconds) {
        if (lastMilliseconds <= currMilliseconds) {
            return false;
        }
        long timeDifferenceMilliseconds = lastMilliseconds - currMilliseconds;
        if (timeDifferenceMilliseconds >= maxTolerateTimeDifferenceMilliseconds) {
            log.error(String.format("Clock is  moving backwards, last time is %d ms, current time is %d ms", lastMilliseconds, currMilliseconds));
        }
        Thread.sleep(timeDifferenceMilliseconds);
        return true;
    }

    private long waitUntilNextTime(final long lastTime) {
        long currTime = System.currentTimeMillis();
        while (currTime <= lastTime) {
            currTime = System.currentTimeMillis();
        }
        return currTime;
    }

    private void vibrateSequenceOffset() {
        sequenceOffset = (byte) (~sequenceOffset & 1);
    }

    public static void main(String[] args) {
        System.out.println(new SnowNoGenerator().generate());
    }
}
